<template>
    <t-head-menu>
        <t-button class="sidebar-trigger" variant="text" @click="toggleSidebar">
            <t-icon :name="settingStore.sidebarCollapsed ? 'menu-unfold' : 'menu-fold'" />
        </t-button>

        <template #operations>
            <t-dropdown trigger="click">
                <template #dropdown>
                    <t-dropdown-menu>
                        <t-dropdown-item class="t-dropdown-item" @click="goToProfile"><user-circle-icon />
                            个人中心</t-dropdown-item>
                        <t-dropdown-item class="t-dropdown-item" @click="logout"><poweroff-icon />
                            退出登录</t-dropdown-item>
                    </t-dropdown-menu>
                </template>
                <t-button theme="default" variant="text">
                    <template #icon>
                        <t-icon name="user-circle" />
                    </template>
                    {{ name }}
                </t-button>
            </t-dropdown>
        </template>
    </t-head-menu>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { useRouter } from 'vue-router';
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next';

import { useUserStore, useSettingStore } from '@/store';
import { UserCircleIcon, PoweroffIcon } from 'tdesign-icons-vue-next';

import { getUserInfo } from '@/api/login';

const router = useRouter();
const userStore = useUserStore();
const settingStore = useSettingStore();

const name = computed(() => userStore.name);

const toggleSidebar = () => {
    settingStore.toggleSidebar();
}

const logout = async () => {
    const dialog = DialogPlugin.confirm({
        header: '确认退出',
        body: '确定要退出系统吗？',
        confirmBtn: '确定',
        cancelBtn: '取消',
        onConfirm: async () => {
            userStore.clearUserInfo();
            MessagePlugin.success('退出登录成功',1000).then(() => {
                dialog.destroy();
                router.push('/login');
            })
        }
    });
}

const goToProfile = async () => {
    try{
        const res = await getUserInfo();
        if(res.role.includes('admin')){
            router.push('/admin/user_profile');
        }else{
            router.push('/user/user_profile');
        }
    }catch(error){
        console.error('获取用户信息失败:', error);
    }
}

</script>
<style scoped>
.t-dropdown-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.sidebar-trigger {
    margin-right: 16px;
}
</style>